#include <QtGui/QApplication>
#include "mainwindow.h"
#include <stdio.h>


void _atexit()
{
    fclose(stdout);
    fclose(stderr);
}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DBusConnector *dbus = 0;

    /*QString _stdout = QString::fromUtf8(argv[0]) + "_stdout.txt";
    QString _stderr = QString::fromUtf8(argv[0]) + "_stderr.txt";

    stdout = freopen(_stdout.toUtf8().data(), "w+", stdout);
    stderr = freopen(_stderr.toUtf8().data(), "w+", stderr);

    atexit(_atexit);*/


    QStringList _args;
    for(int i=1; i<argc; ++i)
    {
        QString name = QObject::trUtf8(argv[i]);
        if(!name.startsWith("/"))
        {
            name = QCoreApplication::applicationDirPath() + "/" + name;
        }

        _args << name;
    }

#ifdef Q_OS_UNIX
    /* коннектимся к шине */
    QDBusConnection connection = QDBusConnection::connectToBus(QDBusConnection::SessionBus, "DBus.Manager.MyDesktopServer");
    if (connection.isConnected())
    {
        qWarning() << QObject::trUtf8("Соединение установлено");

        if (!connection.registerService("DBus.Manager.MyDesktopServer")) {

            if(argc > 1)
            {
                connection = QDBusConnection::connectToBus(QDBusConnection::SessionBus, "DBus.Manager.MyDesktopServer");

                qWarning("Send data\n");
                QDBusMessage msg = QDBusMessage::createMethodCall("DBus.Manager.MyDesktopServer", "/MyDesktopServer",
                                                          "DBus.Manager.MyDesktopServer", "setContent");


                QList<QVariant> args;
                args.append(QVariant(_args));
                msg.setArguments(args);
                connection.send(msg);
                QCoreApplication::processEvents();
                return 0;
            }
        }

        dbus = new DBusConnector(&a);
        if (!connection.registerObject("/MyDesktopServer", dbus, QDBusConnection::ExportAllContents)) {
            qWarning() << QObject::trUtf8("Не могу зарегистрировать объект\n");
            delete dbus;
            dbus = 0;
        }
    } else
    {
        qWarning() << QObject::trUtf8("Внимание! Соеденение с dbus небыло установленно!\n");
    }


#endif

    MainWindow w(dbus);
    w.show();

    if(!_args.isEmpty())
        w.shareNewObjects(_args);

    return a.exec();
}
